<template>
  <div class="wrapper">
    <!--        header部分-->
    <header>
      <p class="back" @click="backToBusinessList">&lt; 返回</p>
      <p >商家信息</p>
    </header>
    <!--        商家logo部分-->
    <div class="business-logo">
      <img :src="business.businessImg">
    </div>
    <!--        商家信息部分-->
    <div class="business-info">
      <h1>{{business.businessName}}</h1>
      <p>&#165;{{business.starPrice}}起送 &#165;{{business.deliveryPrice}}配送</p>
      <p>{{business.businessExplain}}</p>
    </div>
    <!--        食品列表部分-->
    <ul class="food">

      <li v-for="(item,i) in foodList" :key="i" >
        <div class="food-left">
          <img :src="item.foodImg">
          <div class="food-left-info">

            <h3>{{item.foodName}}</h3>
            <p>{{ item.foodExplain }}</p>
            <p>&#165;{{item.foodPrice}}</p>
          </div>
        </div>
        <div class="food-right">
          <div>
<!--            <i class="fa fa-minus-circle"></i>-->
            <img v-if="foodList[i].quantity>0" class="minus" src="src/assets/icons/businessInfo/jian.png" @click="minus(i)">
          </div>
          <p><span v-if="foodList[i].quantity>0">{{foodList[i].quantity}}</span></p>
          <div>
            <img class="plus" src="src/assets/icons/businessInfo/jia.png" @click="add(i)">
<!--            <i class="fa fa-plus-circle"></i>-->
          </div>
        </div>

      </li>

    </ul>

   <Cart :foodList="foodList" :businessId="parseInt(businessId)"  />
  </div>

</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import Cart from "./item/Cart.vue";
import qs from 'qs';
import {getSessionStorage} from "../main.js";
const router = useRouter();
let businessId = ref();
let foodList = ref([]);
let business = reactive({});
let user=ref("")

onMounted(() => {
  user.value=getSessionStorage('user')
  // console.log(router.currentRoute.value.query)
  businessId.value = router.currentRoute.value.query.id;
  getFoodListByBusinessId();
  loadBusiness();
});

// onBeforeUnmount(() => {
//   // console.log("change!!")
//   // console.log(foodList.value)
//   for (let i = 0; i < foodList.value.length; i++) {
//     saveQuantityToLocalStorage(foodList.value[i].foodId, foodList.value[i].quantity);
//   }
// });
function listCart(){
  axios.post('cart/listCart',{
      businessId:businessId.value,
      userId:user.value.userId
    }).then(response=>{
    let cartArr = response.data;
    //遍历所有食品列表
    for(let foodItem of foodList.value){
      foodItem.quantity = 0;
      for(let cartItem of cartArr){
        if(cartItem.foodId==foodItem.foodId){
          foodItem.quantity = cartItem.quantity;
        }
      }
    }
    foodList.value.sort();
  }).catch(error=>{
    console.error(error);
  });
}

async function getFoodListByBusinessId() {
  try {
    const response = await axios.get("/food/getFoodByBusinessId", {
      params: { businessId: businessId.value },
    });
    foodList.value = response.data;
    listCart()
  } catch (error) {
    console.error(error);
  }
}

async function loadBusiness() {
  // console.log(businessId)
  try {
    const response = await axios.get("/business/getBusinessById", {
      params: { businessId: businessId.value },
    });
    Object.assign(business, response.data);
  } catch (error) {
    console.error(error);
  }
}

function backToBusinessList() {
  router.push({ path: "/businessList" });
}

// function addNum(i) {
//   if (foodList.value[i].quantity < 10) foodList.value[i].quantity += 1;
//   else alert("数量不能超过10！");
// }
//
// function minusNum(i) {
//   if (foodList.value[i].quantity > 0) foodList.value[i].quantity -= 1;
// }
function add(index){

  if(foodList.value[index].quantity==0){
    //做insert
    savaCart(index);
  }else{
    //做update
    updateCart(index,1);
  }
}
function minus(index){

  if(foodList.value[index].quantity>1){
    //做update
    updateCart(index,-1);
  }else{
    //做delete
    removeCart(index);
  }
}

function savaCart(index){
  axios.post('Cart/saveCart',qs.stringify({
    businessId:businessId.value,
    userId:user.value.userId,
    foodId:foodList.value[index].foodId
  })).then(response=>{
    if(response.data==1){
      //此食品数量要更新为1；
      foodList.value[index].quantity=1;
      foodList.value.sort();
    }else{
      alert('向购物车中添加食品失败！');
    }
  }).catch(error=>{
    console.error(error);
  });
}
function updateCart(index,num){
  axios.post('Cart/updateCart',qs.stringify({
    businessId:businessId.value,
    userId:user.value.userId,
    foodId:foodList.value[index].foodId,
    quantity:foodList.value[index].quantity+num
  })).then(response=>{
    if(response.data==1){
      //此食品数量要更新为1或-1；
      foodList.value[index].quantity+=num;
      foodList.value.sort();
    }else{
      alert('向购物车中更新食品失败！');
    }
  }).catch(error=>{
    console.error(error);
  });
}
function removeCart(index){
  axios.post('Cart/removeCart',qs.stringify({
    businessId:businessId.value,
    userId:user.value.userId,
    foodId:foodList.value[index].foodId
  })).then(response=>{
    if(response.data==1){
      //此食品数量要更新为0；视图的减号和数量要消失
      foodList.value[index].quantity=0;
      foodList.value.sort();
    }else{
      alert('从购物车中删除食品失败！');
    }
  }).catch(error=>{
    console.error(error);
  });
}
// function saveQuantityToLocalStorage(foodId, quantity) {
//   localStorage.setItem(foodId.toString(), quantity.toString());
// }

// function getQuantityFromLocalStorage(foodId) {
//   const storedQuantity = localStorage.getItem(foodId.toString());
//   return storedQuantity ? parseInt(storedQuantity) : 0;
// }

</script>

<style scoped>
/*总容器*/
.wrapper{
  width: 100%;
  height: 100%;
}
/*header部分*/
.wrapper header{
  width:100%;
  height: 12vw;
  background-color: #0097FF;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;

}
.wrapper header .back{
  position: absolute;
  left:7px;
  display: flex;
  align-items: center;
  text-align: center;
}
/*商家logo部分*/
.wrapper .business-logo{
  width: 100%;
  height: 35vw;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;

}

.wrapper .business-logo img{
  width: 40vw;
  height: 30vw;
  border-radius: 5px;

}

/*商家信息*/
.wrapper .business-info{
  width: 100%;
  height: 20vw;

  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.wrapper .business-info h1{
  font-size: 5vw;

}
.wrapper .business-info p{
  font-size: 3vw;
  color: #666;
  margin-top: 1vw;
}
/*食品列表*/
.wrapper .food{
  width: 100%;
  padding-bottom:14vw ;

}
.wrapper .food li{
  width:100%;
  box-sizing: border-box;
  padding: 2.5vw;
  user-select: none;

  display: flex;
  justify-content: space-between;
  align-items: center;

}
.wrapper .food li .food-left{
  display: flex;
  align-items: center;
}
.wrapper .food li .food-left img{
  width: 20vw;

}
.wrapper .food li .food-left .food-left-info{
  margin-left: 3vw;

}
.wrapper .food li .food-left .food-left-info h3{
  font-size: 3.8vw;
  color: #555;
}
.wrapper .food li .food-left .food-left-info p{
  font-size: 3vw;
  color: #888;
  margin-top: 2vw;
}
.wrapper .food li  .food-right{
  width: 16vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 15px;
}
.wrapper .food li  .food-right .plus{
  width: 20px;
  height: 20px;
  color: #999;
  cursor: pointer;


}
.wrapper .food li  .food-right .minus{
  width: 20px;
  height: 20px;
  color: #999;
  cursor: pointer;
  /*margin-right: 10px;*/

}
.wrapper .food li  .food-right p{
  font-size: 3.6vw;
  color: #333;
  /*margin-left: 10px;*/
  margin: 0 10px;
}


</style>